<template>
    <el-dialog :model-value="visible" title="执行回测" @update:model-value="$emit('update:visible', $event)" width="50%">
        <el-form :model="form" ref="backtestFormRef" label-width="100px" :rules="rules">
            <el-form-item label="起始日期" prop="startDate">
                <el-date-picker v-model="form.startDate" type="date" placeholder="选择起始日期" value-format="YYYY-MM-DD"
                    style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
                <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD"
                    style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="初始资金" prop="initialBalance">
                <el-input-number v-model="form.initialBalance" :precision="2" :step="1000" :min="0" placeholder="输入初始资金"
                    style="width: 100%;"></el-input-number>
            </el-form-item>
        </el-form>

        <div v-if="parsedResult" class="result-container" v-loading="loading">
            <el-divider>回测结果</el-divider>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="初始权益">{{ parsedResult.initialBalance?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="期末权益">{{ parsedResult.finalValue?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="总回报">{{ parsedResult.totalReturn?.toFixed(2) }}</el-descriptions-item>
                <el-descriptions-item label="总回报率">
                    <span :class="getReturnRateColor(parsedResult.totalReturnRate)">
                        {{ (parsedResult.totalReturnRate * 100).toFixed(2) }}%
                    </span>
                </el-descriptions-item>
            </el-descriptions>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">关闭</el-button>
                <el-button type="primary" @click="submitBacktest" :loading="loading">开始回测</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { runBacktest } from '@/api/strategyApi';

const props = defineProps({
    visible: Boolean,
    strategyId: Number,
});

const emit = defineEmits(['update:visible']);

const form = reactive({
    startDate: '',
    endDate: '',
    initialBalance: 1000000,
});
const rules = {
    startDate: [{ required: true, message: '起始日期不能为空', trigger: 'change' }],
    endDate: [{ required: true, message: '结束日期不能为空', trigger: 'change' }],
    initialBalance: [{ required: true, message: '初始资金不能为空', trigger: 'blur' }],
};

const backtestFormRef = ref(null);
const loading = ref(false);
const backtestResult = ref(null);

// 计算属性，用于安全地解析result字段中的JSON字符串
const parsedResult = computed(() => {
    if (backtestResult.value && backtestResult.value.result) {
        try {
            // 后端返回的result已经是JSON对象，无需解析
            return JSON.parse(backtestResult.value.result);
        } catch (e) {
            console.error('解析回测结果JSON失败:', e);
            // 如果解析失败，返回null，模板中不会渲染结果区域
            return null;
        }
    }
    return null;
});

const getReturnRateColor = (rate) => {
    if (rate > 0) return 'color-red';
    if (rate < 0) return 'color-green';
    return '';
};

const closeDialog = () => {
    emit('update:visible', false);
};

// 弹窗关闭时，清空上一次的结果
watch(() => props.visible, (newVal) => {
    if (!newVal) {
        backtestResult.value = null;
    }
});

// 提交回测的逻辑
const submitBacktest = () => {
    backtestFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            backtestResult.value = null; // 开始新回测时清空旧结果
            try {
                const response = await runBacktest(props.strategyId, form);
                backtestResult.value = response.data;
                ElMessage.success('回测成功');
            } catch (error) {
                ElMessage.error('回测失败: ' + (error.response?.data?.message || error.message));
            } finally {
                loading.value = false;
            }
        }
    });
};
</script>

<style scoped>
.result-container {
    margin-top: 20px;
}

/* 定义回报率颜色 */
.color-red {
    color: #F56C6C;
}

.color-green {
    color: #67C23A;
}
</style>